package cn.gzjp.modules.it.scheduler;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;


import cn.gzjp.common.utils.FlowIdUtil;
import cn.gzjp.common.utils.pay.PayUtils;
import cn.gzjp.common.utils.pay.Sha1Util;
import cn.gzjp.modules.gas.entity.GasRecharge;
import cn.gzjp.modules.gas.service.GasRechargeService;
import cn.gzjp.modules.logis.entity.LogisDelivery;
import cn.gzjp.modules.logis.entity.LogisDeliveryLog;
import cn.gzjp.modules.logis.entity.LogisUser;
import cn.gzjp.modules.logis.entity.LogisUserUnion;
import cn.gzjp.modules.logis.service.LogisDeliveryLogService;
import cn.gzjp.modules.logis.service.LogisDeliveryService;
import cn.gzjp.modules.logis.service.LogisUserService;
import cn.gzjp.modules.logis.service.LogisUserUnionService;
import cn.gzjp.modules.wx.entity.WxMpAccount;
import cn.gzjp.modules.wx.service.WxMpAccountService;
import cn.gzjp.modules.wx.service.WxService;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.github.binarywang.wxpay.bean.request.WxPayRefundRequest;
import com.github.binarywang.wxpay.bean.result.WxPayRefundResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;


import cn.gzjp.modules.it.service.CarMoveService;

/**
 * 定时任务
 *
 * @author zengcp
 */
@Service
@Lazy(false)
public class TaskJob {

    public static Logger log = LoggerFactory.getLogger("jobLog");
    @Autowired
    private CarMoveService carMoveService;
    @Autowired
    private LogisDeliveryService logisDeliveryService;
    @Autowired
    private LogisDeliveryLogService logisDeliveryLogService;
    @Autowired
    private WxService wxService;
    @Autowired
    private WxMpAccountService wxMpAccountService;

    @Autowired
    private LogisUserService logisUserService;
    @Autowired
    private GasRechargeService gasRechargeService;
    @Autowired
    private LogisUserUnionService logisUserUnionService;


    public static Map<String,String> prepayIdMap = new ConcurrentHashMap<String, String>();

//    @Scheduled(cron = "0 0/200 * * * ?")
//    public void synchStatus() {
//        log.info("挪车状态定时同步开始");
//        CarMove search = new CarMove();
//        search.setStatus(1);
//        List<CarMove> carMoveList = carMoveService.findList(search);
//        for (CarMove carMove : carMoveList) {
//            try {
//                if (DateUtils.addMinute(carMove.getCreateDate(), 10).before(new Date())) {// 到期了
//                    carMove.setStatus(5);//状态5：系统超时，车主未回应——已产生罚单，再次举报交管将强制处理
//                    carMoveService.save(carMove);
//                    log.info(carMove.getId() + "系统超时，车主未回应——已产生罚单，再次举报交管将强制处理");
//                } else {
//                    log.info(carMove.getId() + "一键挪车未到期");
//                }
//            } catch (Exception e) {
//                // TODO Auto-generated catch block
//                e.printStackTrace();
//            }
//        }
//        log.info("挪车状态定时同步结束");
//    }


    @Scheduled(cron = "0 0/5 * * * ?")
    public void synchDeliveryStatus() {
        log.info("发货单过期定时任务开始.......");
 //       LogisDelivery search = new LogisDelivery();
//        search.setAuditStatus(1);//已发布
//        search.setStatus("2");//等待接单
//        List<LogisDelivery> deliveries = logisDeliveryService.findList(search);
//        for (LogisDelivery delivery : deliveries) {
//            try {
//                if (StrUtil.isNotBlank(delivery.getLoadTime())) {
//                    Date loadTime = DateUtil.endOfDay(DateUtil.parseDate(delivery.getLoadTime()));
//                    if (loadTime.before(new Date())) {// 到期了
//                        delivery.setStatus("10");//状态10：过期
//                        logisDeliveryService.save(delivery);
//                        LogisDeliveryLog deliveryLog = new LogisDeliveryLog();
//                        deliveryLog.setOpenid("admin");
//                        deliveryLog.setDeliveryId(delivery.getId());
//                        deliveryLog.setStatus(delivery.getStatus());
//                        logisDeliveryLogService.save(deliveryLog);
//                        log.info(delivery.getId() + "装车时间超时，订单过期");
//                    } else {
//                        log.info(delivery.getId() + "装车还未超时");
//                    }
//                }
//            } catch (Exception e) {
//                // TODO Auto-generated catch block
//                e.printStackTrace();
//            }
//        }
//        log.info("发货单过期定时任务结束");

        log.info("---发货单支付订金超期(30分钟)定时任务开始...");
        LogisDelivery search = new LogisDelivery();
        search.setPayStatus("0");
        List<LogisDelivery> deliveries = logisDeliveryService.findList(search);
        for (LogisDelivery delivery : deliveries) {
            try {//16订单关闭，超时未付款 17调度失败，司机超时未接单
                if (StrUtil.isNotBlank(delivery.getLoadTime()) && !"16".equals(delivery.getStatus()) && "0".equals(delivery.getPayStatus())) {
                    Date loadTime = DateUtil.offsetMinute(delivery.getCreateDate(), 30);
                    if (loadTime.before(new Date())) {// 订单关闭，超时未付款
                        delivery.setStatus("16");//状态16：订单关闭，超时未付款
                        logisDeliveryService.save(delivery);
                        log.info(delivery.getId() + "支付订金超时，订单过期");
                        LogisDeliveryLog deliveryLog = new LogisDeliveryLog();
                        deliveryLog.setOpenid("admin");
                        deliveryLog.setDeliveryId(delivery.getId());
                        deliveryLog.setStatus(delivery.getStatus());
                        logisDeliveryLogService.save(deliveryLog);



                        String page="pages/gcDdXq/gcDdXq?deliveryId=" + delivery.getId();
                        String keyword1 = delivery.getStartProvince() + delivery.getStartCity();
                        String keyword2 = delivery.getEndProvince() + delivery.getEndCity();
                        String keyword3 = delivery.getId();
                        String keyword4 = "订单已关闭";
                        String keyword5 = "超时未支付订金";
                        String keyword6 = "无";
                        if(StrUtil.isNotBlank(delivery.getCarrierMobile())){
                            keyword6 = delivery.getCarrierMobile();
                        }
                        String keyword7  = "【百灵智慧物流】全国首家标准化物流服务商，透明价格、不负重托、只为更好服务。";
                        if(StrUtil.isNotBlank(delivery.getFormId())){
                            wxService.sendTemplateMsg(delivery.getAppId(),delivery.getDevOpenid(),page,
                                    delivery.getFormId(),keyword1,keyword2,keyword3,keyword4,keyword5,keyword6,keyword7);
                        }

                    } else {
                        log.info(delivery.getId() + "支付订金还未超时");
                    }
                }
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        log.info("---发货单支付订金过期，定时任务结束!!!");


        log.info("---已付订金，司机调度过期(180分钟)定时任务开始...");
        search = new LogisDelivery();
        search.setPayStatus("1");
        search.setStatus("12");//12已付订金，正在调度司机
        deliveries = logisDeliveryService.findList(search);

        search = new LogisDelivery();
        search.setPayStatus("1");
        search.setAuditStatus("0");//客服未审核通过

        List<LogisDelivery> deliveries2 = logisDeliveryService.findList(search);
        deliveries.addAll(deliveries2);
        for (LogisDelivery delivery : deliveries) {
            try {
                Date loadTime = DateUtil.offsetMinute(delivery.getCreateDate(), 180);
                if (loadTime.before(new Date())&&!"17".equals(delivery.getStatus())) {// 到期了
                    delivery.setStatus("17");//调度失败，司机超时未接单
                    logisDeliveryService.save(delivery);
                    log.info(delivery.getId() + "|司机调度过期，退还订金操作开始");
                    LogisDeliveryLog deliveryLog = new LogisDeliveryLog();
                    deliveryLog.setOpenid("admin");
                    deliveryLog.setDeliveryId(delivery.getId());
                    deliveryLog.setStatus(delivery.getStatus());
                    deliveryLog.setType("1");
                    logisDeliveryLogService.save(deliveryLog);

                    if(StrUtil.isNotBlank(delivery.getPayOpenId1())){
                        LogisUser payer = logisUserService.get(delivery.getPayOpenId1());
                        WxPayRefundRequest wxEntPayRequest = new WxPayRefundRequest();
                        WxMpAccount mpAccount = wxMpAccountService.get(payer.getAppId());

                        String mchId = mpAccount.getMchId();
                        String key = mpAccount.getMchKey();
                        wxEntPayRequest.setAppid(payer.getAppId());
                        wxEntPayRequest.setMchId(mchId);
                        wxEntPayRequest.setNonceStr(Sha1Util.getNonceStr());
                        wxEntPayRequest.setTransactionId(delivery.getWxOrderId());
                        wxEntPayRequest.setOutRefundNo(FlowIdUtil.getInstance().getFlowidNoYear() + "");
                        wxEntPayRequest.setTotalFee(delivery.getDeposit().intValue() * 100);
                        wxEntPayRequest.setRefundFee(wxEntPayRequest.getTotalFee());
                        wxEntPayRequest.setRefundDesc("司机超时未接单，定金全额退回");

                        Map<String, String> params = new HashMap<String, String>();
                        params.put("transaction_id", wxEntPayRequest.getTransactionId());
                        params.put("out_refund_no", wxEntPayRequest.getOutRefundNo());
                        params.put("total_fee", String.valueOf(wxEntPayRequest.getTotalFee()));
                        params.put("refund_fee", String.valueOf(wxEntPayRequest.getTotalFee()));
                        params.put("appid", wxEntPayRequest.getAppid());
                        params.put("mch_id", mchId);
                        params.put("op_user_id", mchId);
                        params.put("nonce_str", PayUtils.createNoncestr());
                        wxEntPayRequest.setSign(PayUtils.getSign(params, key));
                        WxPayRefundResult wxEntPayResult = this.wxService.getPayService(payer.getAppId()).refund(wxEntPayRequest);
                        log.info("退款信息：\n" + wxEntPayResult.toString());
                        if ("SUCCESS".equals(wxEntPayResult.getResultCode().toUpperCase())
                                && "SUCCESS".equals(wxEntPayResult.getReturnCode().toUpperCase())) {
                            log.info("退款成功！\n付款信息：\n" + wxEntPayResult.toString());
                        }

                        String page="pages/gcDdXq/gcDdXq?deliveryId=" + delivery.getId();
                        String keyword1 = delivery.getStartProvince() + delivery.getStartCity();
                        String keyword2 = delivery.getEndProvince() + delivery.getEndCity();
                        String keyword3 = delivery.getId();
                        String keyword4 = "调度失败,司机超时未接单";
                        String keyword5 = "司机超时未接单";
                        String keyword6 = "无";
                        if(StrUtil.isNotBlank(delivery.getCarrierMobile())){
                            keyword6 = delivery.getCarrierMobile();
                        }
                        String keyword7  = "【百灵智慧物流】全国首家标准化物流服务商，透明价格、不负重托、只为更好服务。";
                        String formId = TaskJob.prepayIdMap.get(delivery.getId());
                        if(StrUtil.isNotBlank(formId)){
                            //发给工厂
                            wxService.sendTemplateMsg(delivery.getAppId(),delivery.getDevOpenid(),page,
                                    formId,keyword1,keyword2,keyword3,keyword4,keyword5,keyword6,keyword7);
                            keyword5 = "退还订金";
                            page="/pages/hzDd/hzDd?deliveryId=" + delivery.getId()+"&shareOpenid=&shareState=0";
                            //发给货主
                            wxService.sendTemplateMsg(delivery.getAppId(),delivery.getRecOpenid(),page,
                                    formId,keyword1,keyword2,keyword3,keyword4,keyword5,keyword6,keyword7);
                        }

                    }

                } else {
                    //log.info(delivery.getId() + "司机调度还未超时");
                }
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                log.info(delivery.getId() + "出错"+e.getMessage());
            }
        }
        log.info("---已付订金，司机调度过期(180分钟)定时任务结束!!!");
        log.info("已付司机调度过期定时任务，定时任务结束!!!!");

        log.info("开始更新用户余额...");
        List<LogisUserUnion> unionUserList = logisUserUnionService.findList(new LogisUserUnion());
        for(LogisUserUnion userUnion:unionUserList){
            log.info("更新用户余额 unionId="+userUnion.getId());
            GasRecharge gasSearch = new GasRecharge();
            gasSearch.setUnionId(userUnion.getId());
            List<GasRecharge> rewards = this.gasRechargeService.findList(gasSearch);
            BigDecimal balance = new BigDecimal("0");
            for(GasRecharge recharge:rewards){
                balance = balance.add(recharge.getAmount());
            }
            if(balance.intValue()>0){
                userUnion.setBalance(balance);
                logisUserUnionService.save(userUnion);//更新用户余额
            }
        }
        log.info("更新用户余额完成！！！");
    }
}
